import cookielib
import urllib2
import tool
import urllib
from bs4 import BeautifulSoup
class Login:
    cookie_path = 'cookie.txt'
    login_request_url = 'https://accounts.pixiv.net/login'
    login_url = 'https://accounts.pixiv.net/api/login?lang=zh'
    host_url = 'https://www.pixiv.net'
    opener = None
    def __init__(self):
        self.tool = tool.Tool()

    def cookie_login(self):
        cookie = cookielib.MozillaCookieJar()
        cookie.load(self.cookie_path,ignore_discard=True,ignore_expires=True)
        http_cookie_processor = urllib2.HTTPCookieProcessor(cookie)
        opener = urllib2.build_opener(http_cookie_processor)
        self.opener = opener

    def password_login(self,pixiv_id,pixiv_pwd):
        get_http_request_header = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Encoding': 'gzip, deflate, sdch, br',
            'Accept-Language': 'zh-cn,zh;q=0.8',
            'Cache-Control': 'max-age=0',
            'Connection': 'keep-alive',
            'Host': 'accounts.pixiv.net',
            'Upgrade-Insecure-Requests': '1',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
        }
        send_http_request_header = {
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-cn,zh;q=0.8',
            'Connection': 'keep-alive',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Host': 'accounts.pixiv.net',
            'Origin': 'https://accounts.pixiv.net',
            'Referer': 'https://accounts.pixiv.net/login?lang=zh&source=pc&view_type=page&ref=wwwtop_accounts_index',
            'Upgrade-Insecure-Requests': '1',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',
            'X-Requested-With': 'XMLHttpRequest'
        }
        request_get_token = urllib2.Request(
            url = self.login_request_url,
            headers = get_http_request_header
        )
        try:
            cookie = cookielib.MozillaCookieJar(self.cookie_path)
            http_cookie_processor = urllib2.HTTPCookieProcessor(cookie)
            opener = urllib2.build_opener(http_cookie_processor)
            opener.open(request_get_token)
            cookie.save(ignore_discard=True, ignore_expires=True)

            bs = BeautifulSoup(opener.open(self.login_request_url),'html.parser')

            key = self.tool.Get_Post_Key(str(bs))

            data = {}
            data['pixiv_id'] = pixiv_id
            data['password'] = pixiv_pwd
            data['post_key'] = key

            data = urllib.urlencode(data)

            request_send_token = urllib2.Request(
                url = self.login_url,
                data = data,
                headers = send_http_request_header
            )

            cookie = cookielib.MozillaCookieJar(self.cookie_path)
            cookie.load(self.cookie_path,ignore_discard=True,ignore_expires=True)
            http_cookie_processor = urllib2.HTTPCookieProcessor(cookie)
            opener = urllib2.build_opener(http_cookie_processor)
            opener.open(request_send_token)
            cookie.save(ignore_discard=True,ignore_expires=True)
            self.cookie_login()
        except urllib2.URLError,e:
            if hasattr(e, "reason"):
                print "Login Error!!!", e.reason
            return

    def return_opener(self):
        return self.opener

    def print_opener(self):
        print self.opener

    def is_login_success(self):
        bs = BeautifulSoup(self.opener.open(self.host_url),'html.parser')
        str_bs = bs.find_all(attrs='profile')
        #pprint.pprint(str_bs)
        if str_bs:
            return True
        else:
            return False

if __name__ == '__main__':
    login  = Login()
    login.password_login('','')
    print login.is_login_success()